﻿    var map = null;
    
    function pageLoad()
    {
        map = new VEMap('myMap');
        map.LoadMap(new VELatLong(41.85, -87.65), 8);

    }
    
    function getWeather_onclick()
    {
        var lat=$get('lat').value;
        var lng=$get('lng').value;
        velatlong=new VELatLong(lat,lng);
        map.SetCenter(velatlong);
        var centre = map.GetCenter();
        WeatherService.GetWeatherByLocation(centre.Latitude, centre.Longitude, GetWeather_success, onFailed);
        MessageBox(true, "Please wait while retrieving weather data...");
    }
    
    function onFailed(e)
    {
        MessageBox(true, "Error while connecting to the remote web service. Please try again later.", 5000);
    }
    
    function GetWeather_success(e)
    {
        var weatherData = Sys.Serialization.JavaScriptSerializer.deserialize(e);
        var stationsFound = 0;
        
        if (weatherData.weatherObservations && weatherData.weatherObservations.length > 0)
        {
            Array.forEach(weatherData.weatherObservations, AddWeatherPushpin);
            stationsFound = weatherData.weatherObservations.length;
        }
        
        if (stationsFound > 0)
        {
            var message = String.format("Data was retrieved for {0} weather stations.",stationsFound);
            MessageBox(true, message, 2000);    
        }
        else
        {
            MessageBox(true, "No weather data was found. Please try again.", 5000);
        }
    }
    
    function AddWeatherPushpin(observation)
    {
        var icon;
        // The observation time is parsed in order to determine
        // whether the observation was taken during the day or
        // the night and choose an appropriate icon.
        // The format of the returned date is yyyy-MM-dd hh:mm:ss
        var d = observation.datetime;
        var date = new Date(d.substr(0,4), d.substr(5,2), d.substr(8,2),
                            d.substr(11,2), d.substr(14,2), d.substr(17,2));
        
        var isDay = (date.getHours() > 6 && date.getHours() < 20);
           
        switch (observation.clouds)
        {
            case 'clear sky':
                if (isDay) icon = '32'; else icon = '31';
                break;
            case 'few clouds':
                if (isDay) icon = '30'; else icon = '29';
                break;
            case 'scattered clouds':
                if (isDay) icon = '28'; else icon = '27';
                break;
            case 'broken clouds':
                icon = '26';
                break;
            case 'overcast':
            case 'vertical visibility':
                icon = '23';
                break;
            default:
                icon = 'NA';
        }
        // The wind speed is converted from knots to m/s
        var windSpeedMs = Math.round(observation.windSpeed * 0.5144444 * 100)/100;
       
        var html = "<em>{0}</em><br/><b>Clouds:</b> {1}<br/><b>Weather condition:</b> {2}<br/>" +
                "<b>Temperature:</b> {3} °C<br/><b>Dew Point:</b> {4} °C<br/>" +
                "<b>Wind:</b> {5}kt ({6} m/s) from {7}°<br/><b>Altimeter:</b> {8} hPa";
        var details = String.format(html,
                observation.datetime, observation.clouds, observation.weatherCondition, 
                observation.temperature, observation.dewPoint, observation.windSpeed, 
                windSpeedMs, observation.windDirection, observation.hectoPascAltimeter);
        
        icon = String.format("images/{0}.png", icon);
        icon = GetCorrectIcon(icon, 48, 48, -10, -12);
        AddPushpin(observation.lat, observation.lng, observation.stationName, details, icon);
    }
    
    function GetCorrectIcon(iconPath, width, height, offsetLeft, offsetTop)
    {
        /// <summary>Fixes the IE6 png transparency issue for the passed icon</summary>
        var html;
        if (Sys.Browser.agent == Sys.Browser.InternetExplorer && 
            Sys.Browser.version == 6)
            html = "<img src='images/blank.gif' " + 
            "style='position:absolute;left:{0}px;top:{1}px;width:{2}px;height:{3}px;" +
            "filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\"{4}\", " +
            "sizingMethod=\"image\" );' />";
        else
            html = "<img src='{4}' " +
            "style='position:absolute;left:{0}px;top:{1}px;width:{2}px;height:{3}px;' />";
        
        if (!offsetLeft) offsetLeft = 0;
        if (!offsetTop) offsetTop = 0;
        return String.format(html, offsetLeft, offsetTop, width, height, iconPath);
    }    
    
    function AddPushpin(lat, lon, title, description, icon)
    {
        var point = new VELatLong(lat, lon);
        var shp = new VEShape(VEShapeType.Pushpin, point);
        shp.SetTitle(title);
        shp.SetDescription(description);
        if (icon)
        {
            shp.SetCustomIcon(icon);
        }
        map.AddShape(shp);
    }
    
    function MessageBox(show, message, timeout)
    {
        var balloon = $get('messageBalloon');
        if (!show)
            balloon.style.display = 'none';
        else
        {
            balloon.style.display = 'block';
            balloon.innerHTML = message;
            if (timeout)
                setTimeout('MessageBox(false)', timeout);
        }
    }
